from flask import Flask, request, jsonify
import configparser
import redis
from redis.exceptions import RedisError

app = Flask(__name__)

# 加载配置文件
config = configparser.ConfigParser()
config.read('/Users/jinjiakk/项目文件/WORKS/rpa/zmn_ai_kwdb_project/config.ini')

# 初始化Redis连接池
redis_pool = redis.ConnectionPool(
    host=config['redis']['host'],
    port=int(config['redis']['port']),
    password=config['redis'].get('password', ''),
    db=int(config['redis'].get('db', 0)),
    decode_responses=True
)

@app.route('/health', methods=['GET'])
def health_check():
    return jsonify({'status': 'ok', 'service': 'task_api'})

@app.route('/task', methods=['POST'])
def submit_task():
    try:
        data = request.get_json()
        
        # 参数校验
        if not data or 'prd_link' not in data or 'request_id' not in data:
            return jsonify({
                'code': 400,
                'message': 'Missing required parameters: prd_link, request_id'
            }), 400

        # 任务数据预处理
        task_data = {
            'prd_link': data['prd_link'],
            'request_id': data['request_id'],
            'priority': data.get('priority', 'normal')
        }

        # Redis连接和任务推送
        with redis.Redis(connection_pool=redis_pool) as conn:
            conn.rpush('task_queue', str(task_data))

        return jsonify({
            'code': 200,
            'message': 'Task accepted',
            'request_id': data['request_id']
        })

    except RedisError as e:
        return jsonify({
            'code': 503,
            'message': f'Redis service unavailable: {str(e)}'
        }), 503
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'Internal server error: {str(e)}'
        }), 500

if __name__ == '__main__':
    app.run(
        host='0.0.0.0',
        port=5000,
        debug=config.getboolean('flask', 'debug', fallback=False)
    )